package com.my.learn.thread.juc;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.my.learn.thread.TestThread;

import java.util.concurrent.*;

/**
 * 用来控制一个或者多个线程等待多个线程。
 * 维护了一个计数器 cnt，每次调用 countDown() 方法会让计数器的值减 1，减到 0 的时候，那些因为调用 await() 方法而在等待的线程就会被唤醒。
 */
public class CountdownLatchExample {

    private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("test-pool-%d").build();

    private static ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1, namedThreadFactory);
    private static CountDownLatch countDownLatch = null;
    private static boolean flag = true;

    public static void main(String[] args) throws InterruptedException {
        //周期性任务
        scheduledExecutorService.scheduleAtFixedRate(new MyThread(), 5, 5, TimeUnit.SECONDS);
        while(true){
            if (!flag) {
                countDownLatch.await();
                System.out.println("end");
            }
            System.out.println("test");
            Thread.sleep(500);
        }
    }

    public static class MyThread implements Runnable {

        @Override
        public void run() {
            countDownLatch = new CountDownLatch(1);
            flag = false;
            System.out.println("mythread");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            countDownLatch.countDown();
            flag = true;
        }
    }

}
